import torchvision
from torch import nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
import time
import torch
from torchvision.models import *
# transform_train = torchvision.transforms.Compose([
#     torchvision.transforms.Pad(4),
#     torchvision.transforms.RandomHorizontalFlip(),
#     torchvision.transforms.RandomCrop(32),
#     torchvision.transforms.ToTensor()
# ])
train_data = torchvision.datasets.CIFAR10("./data",train=True,
                                          transform=torchvision.transforms.ToTensor(),
                                          download=True)
test_data = torchvision.datasets.CIFAR10("./data",train=False,
                                          transform=torchvision.transforms.ToTensor(),
                                          download=True)
print(train_data[0][0].shape)
# 加载数据集
train_dataloader = DataLoader(train_data,batch_size=64)
test_dataloader = DataLoader(test_data,batch_size=64)

# 神经网络模型
net = torchvision.models.resnet18(resnet.BasicBlock)
# 损失函数
loss_fn = nn.CrossEntropyLoss()
# 创建优化器
learn_rate = 0.05
optimizer = torch.optim.SGD(net.parameters(),lr=learn_rate)
# 设置训练网络的参数
# 记录训练的次数
total_train_step = 0
# 记录测试的次数
total_test_step = 0
# 训练轮数
epoch = 3
# 使用tensorboard观测
writer = SummaryWriter("./logs_train")
for i in range(epoch):
    print("第{}轮训练开始".format(i+1))
    # 训练步骤
    for data in train_dataloader:
        imgs, targets = data
        print(imgs.shape)
        output = net(imgs)
        loss = loss_fn(output,targets)  # 训练的损失
        # 优化模型
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        total_train_step += 1
        if total_train_step % 100 == 0:
            print("训练次数:{},loss:{}".format(total_train_step,loss))
            # 用折线图观测
            writer.add_scalar("tran_loss",loss.item(),total_train_step)
    # 测试步骤
    total_test_loss = 0
    with torch.no_grad():
        for data in test_dataloader:
            imgs, targets = data
            outputs = net(imgs)
            loss = loss_fn(outputs,targets)
            total_test_loss = total_test_loss + loss
    print("整体测试集上的loss:{}".format(total_test_loss.item()))  # 测试的损失
    writer.add_scalar("test_loss",total_test_loss,total_test_step)
    total_test_step += 1

writer.close()